#include "stdafx.h"

#ifndef NO_HIGHGUI_CAM

#include "VideoCapture_OpenCvHighGui.h"

OpenCvHighGui::OpenCvHighGui() {
	this->cam = NULL;
	this->initialised = false;
	this->interacedCapture = false;
}

OpenCvHighGui::~OpenCvHighGui() {
	if(this->initialised) {
		this->closeCam();
	}
}

bool OpenCvHighGui::openCam(unsigned long camId) {
	if(this->initialised) return false;
	this->cam = cvCreateCameraCapture( (int) camId);
    if(this->cam == NULL) {
        return false;
    }
	this->initialised = true;
	return true;
}

bool OpenCvHighGui::closeCam() {
	if(!this->initialised) return false;
	cvReleaseCapture(&this->cam);
	this->cam = NULL;
	this->initialised = false;
	this->interacedCapture = false;
	return true;
}

IplImage* OpenCvHighGui::grabRawImage() {
	return cvQueryFrame(this->cam);
}

int OpenCvHighGui::probeCam(unsigned long manualIPaddress ) {
        if(this->camList.size()>0) this->camList.clear();
	CvCapture* camera = NULL;
	int found = 0;
	int result = 0;
	int index =0;
	for(int i=0; i<1100; i+=100) { // enum { CV_CAP_ANY ... CV_CAP_ANDROID }
		index = 0;
		do {
			camera = cvCreateCameraCapture(i+index);
			if(camera!=NULL) {
				result = cvGrabFrame(camera);
				if(result==1) {
					this->camList.push_back(i+index);
					++found;
				}
				cvReleaseCapture(&camera);
				++index;
                        }
                        std::clog<<"Cam #"<<i+index<<" tried.\n";
                } while(result!=NULL && camera!=NULL);
	}
        std::clog<<"All HighGui Cam tried\n";
	return this->camList.size();
}

bool OpenCvHighGui::getCamId(int index, unsigned long &camId, std::string *camName) {
	std::stringstream ss;
	if(index > this->camList.size()) return false;
	camId = (unsigned long) this->camList.at(index);
	if(camName!=NULL) {
		ss << "HighGui Cam #"<<camId;
		camName->assign(ss.str());
	}
	return true;
}

bool OpenCvHighGui::setImageSize(unsigned int width, unsigned int height, unsigned int bytesPerChannel, unsigned int channels) {
	int result = 0;
	result = cvSetCaptureProperty(this->cam,CV_CAP_PROP_FRAME_WIDTH ,width);
	if(result!=1) return false;
	result = cvSetCaptureProperty(this->cam,CV_CAP_PROP_FRAME_HEIGHT ,height);
	if(result!=1) return false;
	return true;
}

	bool OpenCvHighGui::getCamProperties(unsigned long propId, double &value) {
		value = cvGetCaptureProperty(this->cam , (int) propId);
		return true;
	}
	bool OpenCvHighGui::setCamProperties(unsigned long propId, double value) {
		int result = 0;
		result = cvSetCaptureProperty(this->cam, (int) propId, value);
		if(result!=1) return false;
		return true;
	}

#endif
